<template>
  <el-upload
    class="avatar-uploader"
    action="1"
    :limit="1"
    :http-request="httpRequest"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :on-success="onSuccess"
    :file-list="fileList"
    :before-upload="beforeUpload"
    :on-exceed="onExceed"
    sizi="mini"
    list-type="picture"
  >
    <el-button size="small" type="primary" id="upbotton">点击上传</el-button>
    <div slot="tip" class="el-upload__tip" id="tip">图片不能超过2M 上传图片为400*400</div>
  </el-upload>
</template>
<script>
export default {
  name: "upimg",
  //   upurl: "",
  props: ["upurl"],
  data() {
    return {
      fileList: [],
      headers: {},
      datas: {},
      path: ""
    };
  },
  mounted() {},
  methods: {
    handleRemove() {
      //   console.log(file, fileList);
      let tip = document.getElementsByClassName("el-upload")[0];
      tip.style.display = "block";
      let upbotton = document.getElementById("tip");
      upbotton.style.display = "block";
    },
    cliearList(data) {
      if (data) {
        this.fileList.push({ name: "封面图片", url: data });
        let tip = document.getElementsByClassName("el-upload")[0];
        tip.style.display = "none";
        let upbotton = document.getElementById("tip");
        upbotton.style.display = "none";
      } else {
        this.fileList = [];
      }
    },
    handlePreview() {
      //   console.log(file);
    },
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isLt2M;
    },
    httpRequest(file) {
      let formData = new FormData();

      formData.append("image", file.file);
      this.$store
        .dispatch("upimg", formData)
        .then(result => {
          let tip = document.getElementsByClassName("el-upload")[0];
          tip.style.display = "none";
          let upbotton = document.getElementById("tip");
          upbotton.style.display = "none";
          // if (result.code === 0) {
          this.path = result.data.path;
          console.log(this.path);
          this.$emit("getpath", this.path);
          this.$message({
            type: "success",
            message: "上传成功"
          });
          // } else {
          //   this.$message.error("上传失败");
          // }
        })
        .catch(err => {
          console.error(err);
        });
    },
    onExceed() {
      this.$message({
        type: "warning",
        message: "只能上传一张图片哦"
      });
    },
    onSuccess(data) {
      console.log(data, 1111111);
    },
    clearFiles() {
      console.log(12555);
    }
  }
};
</script>
